/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.jmooc.servlets;

import com.jmooc.entity.Answer;
import com.jmooc.entity.Course;
import com.jmooc.entity.Question;
import com.jmooc.entity.User;
import com.jmooc.entity.UserCertification;
import com.jmooc.service.CourseService;
import com.jmooc.service.QuestionService;
import com.jmooc.service.UserCertificationService;
import com.jmooc.service.UserService;
import java.io.IOException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Group
 */
@WebServlet(name = "QuizzServlet", urlPatterns = {"/quizz/*"} )
public class QuizzServlet extends HttpServlet {

    @EJB
    private QuestionService questionService;
    
    @EJB
    private CourseService courseService;
    
    @EJB
    private UserService userService;
    
    @EJB
    private UserCertificationService userCertificationService;
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        Long courseId = Long.valueOf(request.getPathInfo().substring(1));
        
        List<Question> questionList = null;
        
        try {
            Course course = courseService.getById(courseId);
            questionList = questionService.getByCourse(course);
            
        } catch (Exception e) {
            session.setAttribute("message", "Ce cours n'existe pas ou plus");
        }
        
        request.setAttribute("questions", questionList);
        request.getRequestDispatcher("/jsp/quizz.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        
        Long courseId = Long.valueOf(request.getPathInfo().substring(1));
        
        try {
            Course course = courseService.getById(courseId);
            List<Question> questionList = questionService.getByCourse(course);
            int correctAnswers = 0;
            int passingScore = (int) Math.ceil(0.75f * (float)questionList.size());
            
            for (Iterator<Question> it = questionList.iterator(); it.hasNext();) {
                Question question = it.next();
                
                Answer correctAnswer = question.getGoodAnswer();
                
                if (correctAnswer.getId() == Long.valueOf(request.getParameter("question" + question.getId())))
                    correctAnswers++;
            }
            
            User user = userService.getById((Long)session.getAttribute("userId"));
            
            if (correctAnswers >= passingScore) {
                boolean hasCourseCertifications = false;
                
                List<UserCertification> certifications = userCertificationService.getAllByUser(user);
                
                for (Iterator<UserCertification> it = certifications.iterator(); it.hasNext();) {
                    UserCertification userCertification = it.next();
                    
                    if (userCertification.getCourse().getId() == course.getId())
                        hasCourseCertifications = true;
                }   
                
                if (!hasCourseCertifications) {
                    UserCertification certification = new UserCertification();
                    certification.setCourse(course);
                    certification.setUser(user);
                    certification.setObtentionDate(new Date());
                    userCertificationService.create(certification);
                }
                else
                    session.setAttribute("message", "Vous aviez déjà la certification. Mais vous l'auriez eu à nouveau !");
            }

            session.setAttribute("score", Math.round(100 * correctAnswers / questionList.size()));
            session.setAttribute("course", course);
            session.setAttribute("correctAnswers", correctAnswers);            
        } catch (Exception e) {
            e.printStackTrace();
            session.setAttribute("message", "Ce cours n'existe pas ou plus");
        }
        
        request.getRequestDispatcher("/jsp/quizzresult.jsp").forward(request, response);
    }

    
}
